import React, { Component, useState, useEffect } from "react";
/* eslint-disable jsx-a11y/anchor-is-valid */
import {
  Table,
  Input,
  InputNumber,
  Form,
  Typography,
  Spin,
  Button,
  Modal,
  Space,
} from "antd";
import http from "../../network/http";
import dayjs from "dayjs";
const { TextArea } = Input;

const EditableCell = ({
  editing,
  dataIndex,
  title,
  inputType,
  record,
  index,
  children,
  ...restProps
}) => {
  const inputNode = inputType === "number" ? <InputNumber /> : <Input />;
  return (
    <td {...restProps}>
      {editing ? (
        <Form.Item
          name={dataIndex}
          style={{
            margin: 0,
          }}
          rules={[
            {
              required: true,
              message: `Please Input ${title}!`,
            },
          ]}
        >
          {inputNode}
        </Form.Item>
      ) : (
        children
      )}
    </td>
  );
};
export default class News extends Component {
  state = {
    formData: [],
    showEdit: false,
    selectItem: null,
    submitLoading: false,
  };
  getData = async () => {
    this.setState({
      loading: true,
    });
    const res = await this.http("Article");
    this.setState({
      formData: res.data.dtos,
    });
  };
  handleAdd = async (e) => {
    this.setState({ submitLoading: true });
    await this.http("Article", e, "POST", true);
    this.setState({ submitLoading: false, showEdit: false });
    this.getData();
  };
  componentDidMount() {
    this.getData();
  }
  render() {
    return (
      <div>
        <Button
          style={{ margin: "20px" }}
          onClick={() => {
            this.setState({ showEdit: true });
          }}
          type="primary"
        >
          新增
        </Button>
        <Modal
          visible={this.state.showEdit}
          onCancel={() => {
            this.setState({
              showEdit: false,
            });
          }}
          footer={[null, null]}
        >
          <Form name="add" onFinish={this.handleAdd}>
            <Form.Item
              label="简要"
              name="brief"
              rules={[
                {
                  required: true,
                  message: "简要不可为空！",
                },
              ]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              label="内容名称"
              name="title"
              rules={[
                {
                  required: true,
                  message: "内容不可为空！",
                },
              ]}
            >
              <TextArea />
            </Form.Item>
            <Form.Item>
              <Button
                loading={this.state.submitLoading}
                type="primary"
                htmlType="submit"
              >
                提交
              </Button>
            </Form.Item>
          </Form>
        </Modal>
        <EditableTable refresh={this.getData} formData={this.state.formData} />
      </div>
    );
  }
}
const EditableTable = (props) => {
  const [form] = Form.useForm();
  const [data, setData] = useState(props.formData);
  const [editingKey, setEditingKey] = useState("");
  const [loading, setLoading] = useState(false);
  const [showModal, setShowModal] = useState(false);
  const [item, setItem] = useState(null);
  const isEditing = (record) => record.id === editingKey;
  useEffect(() => {
    setData(props.formData);
  }, [props.formData]);
  const edit = (record) => {
    console.log(record);
    form.setFieldsValue({
      sysName: "",
      value: "",
      ...record,
    });
    setEditingKey(record.id);
  };
  const cancel = () => {
    setEditingKey("");
  };
  const deleteItem = async () => {
    // console.log(item);
    // return;
    setLoading(true);
    await http("Article/" + item.id, {}, "DELETE");
    setLoading(false);
    props.refresh();
  };
  const save = async (value) => {
    const row = await form.validateFields();
    const newData = [...data];
    const index = newData.findIndex((item) => value.id === item.id);
    // console.log({
    //   id: value.id,
    //   ...row,
    // });
    // return;
    if (index > -1) {
      setLoading(true);
      const res = await http(
        "Article",
        {
          id: value.id,
          ...row,
        },
        "POST",
        true
      );
      console.log(res);
      setLoading(false);
      props.refresh();
      setEditingKey("");
    }
  };
  const columns = [
    {
      title: "创建时间",
      dataIndex: "createTime",
      render: (e) => dayjs(e).format("YYYY-MM-DD HH:mm"),
    },
    {
      title: "简要",
      dataIndex: "brief",
      editable: true,
    },
    {
      title: "内容",
      dataIndex: "title",
      editable: true,
    },
    {
      title: "操作",
      dataIndex: "operation",
      key: "id",
      render: (_, record) => {
        const editable = isEditing(record);
        return editable ? (
          <span>
            <Button
              size="small"
              type="primary"
              onClick={() => save(record)}
              style={{
                marginRight: 12,
              }}
            >
              保存
            </Button>
            <Button size="small" type="primary" onClick={cancel}>
              取消
            </Button>
          </span>
        ) : (
          <Space>
            <Typography.Link
              disabled={editingKey !== ""}
              onClick={() => edit(record)}
            >
              编辑
            </Typography.Link>
            <Typography.Link
              disabled={editingKey !== ""}
              onClick={() => {
                setShowModal(true);
                setItem(record);
              }}
            >
              删除
            </Typography.Link>
          </Space>
        );
      },
    },
  ];
  const mergedColumns = columns.map((col) => {
    if (!col.editable) {
      return col;
    }
    return {
      ...col,
      onCell: (record) => ({
        record,
        inputType: "text",
        dataIndex: col.dataIndex,
        title: col.title,
        editing: isEditing(record),
      }),
    };
  });
  return (
    <Spin spinning={loading}>
      <Modal
        title=""
        visible={showModal}
        onCancel={() => setShowModal(false)}
        onOk={() => {
          setShowModal(false);
          deleteItem();
        }}
      >
        确认删除吗？
      </Modal>
      <Form form={form} component={false}>
        <Table
          components={{
            body: {
              cell: EditableCell,
            },
          }}
          bordered
          rowKey={(data) => data.id}
          dataSource={data}
          columns={mergedColumns}
          rowClassName="editable-row"
          pagination={{
            onChange: cancel,
          }}
        />
      </Form>
    </Spin>
  );
};
